import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.io.FileUtils;
import sql.query.ObjectVisitor;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class JsonManager implements ObjectVisitor {
    public List<Object> readTable(String tableName) {
        try {
            String content = FileUtils.readFileToString(new File(tableName + ".json"), StandardCharsets.UTF_8);
            return JSON.parseArray(content);
        } catch (IOException e) {
            e.printStackTrace();
            return new JSONArray();
        }
    }

    public  void writeTable(String tableName, List jsonArray) {
        try {
            FileUtils.writeStringToFile(
                    new File(tableName + ".json"),
                    JSON.toJSONString(jsonArray,true),
                    StandardCharsets.UTF_8
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
